package com.cssw.fyzb.busi.api.user;

import com.cssw.fyzb.core.model.dodb.User;
import com.cssw.fyzb.core.model.vo.user.UpdateTradePwdVo;
import com.cssw.fyzb.busi.service.user.UserService;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplecache.SimpleCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.cssw.fyzb.busi.cache.CacheKeys.forUpdateTradePwd;
import static com.cssw.fyzb.busi.util.Bizs.*;

/**
 * @author Feng Chen
 */
@Function(description = "修改交易密码", parameters = {
        @Parameter(name = "mobile", type = Type.Integer, description = "手机号", required = true),
        @Parameter(name = "tradePwd", type = Type.Integer, description = "交易密码", required = true)
})
@Component
public class UpdateTradePwd implements Action {

    @Autowired
    private UserService userService;

    @Autowired
    private SimpleCache simpleCache;

    private static final Logger logger = LoggerFactory.getLogger(UpdateTradePwd.class);

    @Override
    public Response execute(Request request) throws Exception {
        String mobile = request.getString("mobile");
        String tradePwd = request.getString("tradePwd");
        try {
            UpdateTradePwdVo updateTradePwdVo = simpleCache.get(forUpdateTradePwd(mobile));
            if (tradePwd == null || tradePwd.length() < 6 || tradePwd.length() > 6) {
                return Response.fail(ERROR_FORMAT_TRADE_PWD.message, ERROR_FORMAT_TRADE_PWD.code);
            }
//            if (updateTradePwdVo == null) {
//                logger.error("缓存不存在或者已失效");
//                return Response.fail("缓存不存在或者已失效");
//            }
            User user = userService.getByMobile(mobile);
            if (user == null) {
                return Response.fail(USER_NOT_EXISTS.message, USER_NOT_EXISTS.code);
            }
            userService.updateTradePwd(user.getUserId(),mobile, tradePwd);
            return Response.success();
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("更新用户等级定义失败");
        }
    }

}
